
package com.e885.util.numeric;

import com.e885.exception.E885UtilException;

/**
 * <br>
 * Copyright: Copyright (c) 2001-2008<br>
 * Company: E885 Group
 * 
 * @author Eric.Kao(gau168.gau@msa.hinet.net)
 * @version 1.0
 */

public class DoubleUtil
{
	/**
	 * Parse String to be primitive int.<br>
	 * If the instance of the String(source) is null or its length is zero, we will return 0.0.<br>
	 * 
	 * @param source to be parsed
	 * @return a primitive double
	 * @throws E885UtilException can't parse string to be primitive double
	 */
	public static double parseString2Primitive( String source ) throws E885UtilException
	{
		return doubleValue( parseString2Double( source ) );
	}

	/**
	 * Parse String to be Double. If sorce is null or the length is zero, we will return null.
	 * 
	 * @param source to be parsed
	 * @return a Double
	 * @throws E885UtilException can't parse string to be Double
	 */
	public static Double parseString2Double( String source ) throws E885UtilException
	{
		if( source == null || source.trim().length() == 0 )
			return null;

		try
		{
			return new Double( source );
		}
		catch( NumberFormatException ex )
		{
			throw new E885UtilException( "can't parse string to be Double:" + source );
		}
	}

	/**
	 * When the argument is null, we will return 0.0.<br>
	 * Otherwise, we will return Double.doubleValue()<br>
	 * reference:{@link java.lang.Double#doubleValue()}
	 * 
	 * @param obj
	 * @return
	 */
	public static double doubleValue( Double obj )
	{
		if( obj == null )
			return 0.0;
		else
			return obj.doubleValue();
	}

	/**
	 * 取得小數點第 N 位, 並做四捨五入
	 * 
	 * @param value 原值
	 * @param idx 取得小數點第 N 位
	 * @return
	 */
	public static double doubleValueByPoint( double value, int idx )
	{
		if( idx < 0 )
			throw new IllegalArgumentException( "the value of the idx is error" );

		return ( int )( value * Math.pow( 10.0, ( double )idx ) + 0.5 ) / Math.pow( 10.0, ( double )idx );
	}
}
